<?php
// $Id: Controller.php 609 2012-12-17 01:23:51Z tomqin@gmail.com $

/**
 * Part of the framework.
 *
 * @package     Library
 * @version     1.0
 * @copyright   Copyright (C) 2010-2012 SupeFun.com Inc.
 * @author      TomQin <tomqin@gmail.com>
 * @license     http://www.supefun.com/license/
 */

class Controller
{

    public $action;
    //public $module;
    //public $control;

    public $var = array();

    public function setAction($action) {
        $this->action = $action;
    }

    public function setVar($key, $var) {
        $this->var[$key] = $var;
    }

    public function getVar($key) {
        return isset($this->var[$key]) ? $this->var[$key] : null;
    }

    public function defaultAction(){
        exit('无效的输入');
    }

    public function beforeAction(){}

    public function afterAction(){}

    public function run(){
        if(Base::isAjaxRequest()){
            $method = 'ajax';
        }else{
            $method = Base::getRequestMethod();
        }

        $action  = $this->action.ucfirst($method).'Action';
        $default = $this->action.'Action';
        $this->beforeAction();
        if(method_exists($this, $action)){
            $this->$action();
        }elseif(method_exists($this, $default)){
            $this->$default();
        }else{
            $this->defaultAction();
        }
        $this->afterAction();
    }

    public function render($tpl) {
        extract($this->var);
        include BASE_PATH.'source'.DS.'template'.DS.str_replace('.', DS, $tpl).'.tpl.php';

        $this->afterAction();
        exit();
    }

    public function renderJSON(array $arr) {
        echo json_encode($arr);

        $this->afterAction();
        exit();
    }

    //载入控制器
    static public function loadController($folder, $module, $control){
        $module  = strtolower($module);
        $control = strtolower($control);
        $class   = ucfirst($control).'Controller';
        if(empty($module)){
            $class = "controller.{$folder}.{$class}";
        }else{
            $class = "controller.{$folder}.{$module}.{$class}";
        }
        return Base::getObject($class);
    }

    //构造器
    public function __construct(){}

    //析构器
    public function __destory(){}
}
